package com.sky.interceptor;

import com.sky.constant.JwtClaimsConstant;
import com.sky.context.BaseContext;
import com.sky.properties.JwtProperties;
import com.sky.utils.JwtUtil;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * jwt令牌校验的拦截器
 */
@Component
@Slf4j
public class JwtTokenAdminInterceptor implements HandlerInterceptor {

    @Autowired
    private JwtProperties jwtProperties;

    /**
     * 校验jwt
     *
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String s = request.getRequestURL().toString();
        log.error("url:{}",s);


        //判断当前拦截到的是Controller的方法还是其他资源
        if (!(handler instanceof HandlerMethod)) {

            //当前拦截到的不是动态方法，直接放行
            return true;
        }

		// 获取token
        String token = request.getHeader("token");
        //不为空 解析
        if(token!=null){
            Claims claimsBody = JwtUtil.getClaimsBody(token);   //  IllegalArgumentException null ,   ExpiredJwtException
            //状态判断 是否过期
            int status = JwtUtil.verifyToken(claimsBody);
            //过期返回401 , status: -1：有效，0：有效，1：过期，2：过期
            if (status == 1 || status == 2){
                response.setStatus(HttpStatus.UNAUTHORIZED.value());

                log.error("JWT过期");
                return false;
            }else {
                //发行前，先将id放到threadlocal中
                Long id = claimsBody.get("id", Long.class);
                System.out.println("id:");
                BaseContext.setCurrentId(id);
                log.error("发行");
                return true;
            }

        }else{
			//没有登录返回，发送未认证错误信息
			response.setStatus(401);
            log.error("JWT不存在");
            return false;
        }
    }
}
